#include <REGX52.H>
#include "timer0.h"
#include "key.h"
#include "AT24C02.h"
#include "delay.h"
#include "nixie.h"

unsigned char keyNumber;
unsigned char minute, second, miniSecond;
unsigned char runFlag;

void main()
{
	timer0_init();
	
	while(1)
	{
		keyNumber = getKey();
		// 键盘1按下, 控制秒表启动和停止
		if(keyNumber == 1)
		{
			// 启动标志位反转
			runFlag = !runFlag;
		}
		// 键盘2按下，秒表清0
		else if(keyNumber == 2)
		{
			minute = 0;
			second = 0;
			miniSecond = 0;
			// 暂停秒表
			runFlag = 0;
		}
		// 键盘3按下，把当前秒表值存入AT24C02
		else if(keyNumber == 3)
		{
			AT24C02_writeByte(0, minute);
			delay(5);
			AT24C02_writeByte(1, second);
			delay(5);
			AT24C02_writeByte(2, miniSecond);
			delay(5);
		}
		// 键盘4按下，从AT24C02中读出秒表值
		else if(keyNumber == 4)
		{
			minute = AT24C02_readByte(0);
			second = AT24C02_readByte(1);
			miniSecond = AT24C02_readByte(2);
			// 暂停秒表
			runFlag = 0;
		}
		
		// 设置显存缓存，显示数据
		nixieTube_setBuf(1, minute/10);
		nixieTube_setBuf(2, minute%10);
		nixieTube_setBuf(3, 11);
		nixieTube_setBuf(4, second/10);
		nixieTube_setBuf(5, second%10);
		nixieTube_setBuf(6, 11);
		nixieTube_setBuf(7, miniSecond/10);
		nixieTube_setBuf(8, miniSecond%10);
	}
}

/** @bref 秒表驱动函数，在定时器中断中调用
  * @param 无
  * @retval 无
  */
void sec_loop()
{
	if(runFlag)
	{
		miniSecond++;
		if(miniSecond > 99)
		{
			miniSecond = 0;
			second++;
			if(second > 59)
			{
				second = 0;
				minute++;
				if(minute > 59)
				{
					minute = 0;
				}
			}
		}
	}
}

/** @bref 定时器中断函数
  * @param 无
  * @retval 无
  */
void Time0_Rountine() interrupt 1
{
	static unsigned int t0Count1, t0Count2, t0Count3;
	TL0 = 0x18;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	
	t0Count1++; //t0Count计次，对中断频率进行分频
	// 分频1000次，大于1s，计数器重置为0
	if(t0Count1 >= 20)
	{
		t0Count1 = 0;
		key_loop();
	}
	t0Count2++;
	if(t0Count2 >= 2)
	{
		t0Count2 = 0;
		nixieTube_loop();
	}
	t0Count3++;
	if(t0Count3 >= 10)
	{
		t0Count3 = 0;
		sec_loop();
	}
}